<script setup>
import { onMounted, ref } from "vue";

const props = defineProps({
  file: {
    type: Object,
    default: () => {},
  },
  // 上传文件大小限制
  fileCapacity: {
    type: Number,
    default: () => 2,
  },
  // 上传文件类型限制
  fileType: {
    type: String,
    default: () => ".jpg,.png,.jpeg",
  },
  buttonText: {
    type: String,
    default: () => "",
  },
  upLoadDisabled: {
    type: Boolean,
    default: () => false,
  },
});
const emit = defineEmits(["uploadFile"]);

const beforeUpload = (file) => {
  const isFile =
    props.fileType === "all" ? true : props.fileType.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < props.fileCapacity;
  if (!isFile) {
    ElMessage.error(`请选择${props.fileType}文件上传`);
  }
  if (!isLt2M) {
    ElMessage.error(`文件不得大于${props.fileCapacity}M！`);
  }
  return isFile && isLt2M;
};
// 文件触发
const fileHandleChange = (file) => {
  emit("uploadFile", file.raw);
};
</script>
<template>
  <div class="m-upload">
    <el-upload
      :accept="fileType === 'all' ? '' : fileType"
      action=""
      :show-file-list="false"
      :auto-upload="false"
      :multiple="false"
      :on-change="fileHandleChange"
      :before-upload="beforeUpload"
      :disabled="upLoadDisabled"
    >
      <el-button
        size="small"
        type="primary"
        class="mr-1 ml-1"
        v-if="buttonText.length != 0"
      >
        {{ buttonText }}
      </el-button>
      <slot name="in-upload"></slot>
      <div slot="tip">
        <slot name="tip-slot"></slot>
      </div>
    </el-upload>
  </div>
</template>
<style lang="scss"></style>
